package com.bnd.utils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Objects;

public class TimeUtils {
    private static final DateTimeFormatter formatter =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

    public static String getTimestamp() {
        return LocalDateTime.now().format(formatter);
    }

    /**
     * 将LocalDateTime格式化为字符串
     * @param localDateTime 需要格式化的时间
     * @return 格式化后的时间字符串
     */
    public static String format(LocalDateTime localDateTime) {
        return Objects.requireNonNullElseGet(localDateTime, LocalDateTime::now).format(formatter);
    }

    /**
     * 将String类型的时间戳转换成LocalDateTime对象
     * @param timestamp 时间戳字符串，格式应为 "yyyy-MM-dd HH:mm:ss.SSS"
     * @return LocalDateTime对象
     * @throws DateTimeParseException 当时间字符串格式不正确时抛出异常
     */
    public static LocalDateTime parseToLocalDateTime(String timestamp) throws DateTimeParseException {
        if (timestamp == null || timestamp.trim().isEmpty()) {
            return null;
        }
        return LocalDateTime.parse(timestamp, formatter);
    }
}
